package cn.lb.framework.poi.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 获取唯一ID工具类
 * Created by Administrator on 2016/4/26.
 */
public final class UniqueIdUtil {

    private static Integer machineId=1;//暂时写死

    private Lock lock = new ReentrantLock();// 锁对象

    private static String numTimeStamp;

    private static int serialNum;

    private static final UniqueIdUtil single = new UniqueIdUtil();

    private UniqueIdUtil() {
        numTimeStamp = new SimpleDateFormat("yyMMddHHmmssSSS").format(new Date());
        machineId = 1;// 需要读取配置不同服务的机器号要不一样
        serialNum = 0;
    }

    public static UniqueIdUtil getInstance() {
        return single;
    }

    public synchronized long getId() {
        lock.lock();// 得到锁
        try {
            long result = 0;
            // 1.拿到当前的时间戳
            String str = new SimpleDateFormat("yyMMddHHmmssSSS").format(new Date());
            if (numTimeStamp.equals(str)) {
                // 同一毫秒生成
                serialNum++;
                if (serialNum >= 100) {
                    throw new RuntimeException("流水号溢出");
                }
            } else {
                numTimeStamp = str;
                serialNum = 0;
            }
            int num = machineId * 100;
            num += serialNum;
            result = Long.valueOf(numTimeStamp + String.valueOf(num));
            return result;
        } finally {
            lock.unlock();// 释放锁
        }
    }

    public static void main(String[] args){
        for(int i=0;i<10;i++)
         System.out.println(UniqueIdUtil.getInstance().getId());
    }
}
